// 全局变量
let selectedImages = [];
let selectedTextImage = null;

// 初始化拖放功能
function initDropZones() {
    const dropZone = document.getElementById('dropZone');
    const textDropZone = document.getElementById('textDropZone');

    // 图片转PDF的拖放区域
    ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, preventDefaults, false);
        textDropZone.addEventListener(eventName, preventDefaults, false);
    });

    function preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    ['dragenter', 'dragover'].forEach(eventName => {
        dropZone.addEventListener(eventName, highlight, false);
        textDropZone.addEventListener(eventName, highlight, false);
    });

    ['dragleave', 'drop'].forEach(eventName => {
        dropZone.addEventListener(eventName, unhighlight, false);
        textDropZone.addEventListener(eventName, unhighlight, false);
    });

    function highlight(e) {
        e.currentTarget.classList.add('dragover');
    }

    function unhighlight(e) {
        e.currentTarget.classList.remove('dragover');
    }

    // 处理文件拖放
    dropZone.addEventListener('drop', handleDrop, false);
    textDropZone.addEventListener('drop', handleTextDrop, false);

    function handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleFiles(files);
    }

    function handleTextDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        handleTextFile(files[0]);
    }
}

// 处理文件选择
document.getElementById('imageInput').addEventListener('change', function(e) {
    handleFiles(e.target.files);
});

document.getElementById('textImageInput').addEventListener('change', function(e) {
    handleTextFile(e.target.files[0]);
});

// 处理多个图片文件
function handleFiles(files) {
    selectedImages = Array.from(files);
    const preview = document.getElementById('imagePreview');
    preview.innerHTML = '';

    selectedImages.forEach((file, index) => {
        const reader = new FileReader();
        reader.onload = function(e) {
            const div = document.createElement('div');
            div.className = 'preview-item';
            div.innerHTML = `
                <img src="${e.target.result}" alt="预览图">
                <button class="remove-btn" onclick="removeImage(${index})">
                    <i class="fas fa-times"></i>
                </button>
            `;
            preview.appendChild(div);
        };
        reader.readAsDataURL(file);
    });
}

// 处理单个图片文件
function handleTextFile(file) {
    if (!file) return;
    
    selectedTextImage = file;
    const reader = new FileReader();
    reader.onload = function(e) {
        const preview = document.getElementById('textImagePreview');
        const img = document.getElementById('previewImage');
        img.src = e.target.result;
        preview.classList.remove('hidden');
    };
    reader.readAsDataURL(file);
}

// 移除图片
function removeImage(index) {
    selectedImages.splice(index, 1);
    handleFiles(selectedImages);
}

// 转换为PDF
async function convertToPDF() {
    if (selectedImages.length === 0) {
        alert('请选择至少一张图片');
        return;
    }

    showLoading();
    const formData = new FormData();
    selectedImages.forEach(file => {
        formData.append('files', file);
    });
    formData.append('dpi', document.getElementById('dpiInput').value);

    try {
        const response = await fetch('/api/images/to-pdf', {
            method: 'POST',
            body: formData
        });

        if (response.ok) {
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'output.pdf';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            a.remove();
        } else {
            throw new Error('转换失败');
        }
    } catch (error) {
        alert('转换失败: ' + error.message);
    } finally {
        hideLoading();
    }
}

// 转换为文字
async function convertToText() {
    if (!selectedTextImage) {
        alert('请选择一张图片');
        return;
    }

    showLoading();
    const formData = new FormData();
    formData.append('file', selectedTextImage);
    formData.append('lang', document.getElementById('langSelect').value);

    try {
        const response = await fetch('/api/images/to-text', {
            method: 'POST',
            body: formData
        });

        if (response.ok) {
            const result = await response.json();
            showResult(result.text);
        } else {
            throw new Error('转换失败');
        }
    } catch (error) {
        alert('转换失败: ' + error.message);
    } finally {
        hideLoading();
    }
}

// 显示结果
function showResult(text) {
    const resultArea = document.getElementById('resultArea');
    const resultContent = document.getElementById('resultContent');
    resultContent.textContent = text;
    resultArea.classList.remove('hidden');
    resultArea.classList.add('fade-in');
}

// 复制结果
function copyResult() {
    const text = document.getElementById('resultContent').textContent;
    navigator.clipboard.writeText(text).then(() => {
        alert('已复制到剪贴板');
    }).catch(err => {
        alert('复制失败: ' + err);
    });
}

// 显示加载动画
function showLoading() {
    document.getElementById('loadingOverlay').classList.remove('hidden');
}

// 隐藏加载动画
function hideLoading() {
    document.getElementById('loadingOverlay').classList.add('hidden');
}

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initDropZones();
}); 